﻿using Common.Interfaces;
using Newtonsoft.Json;
using System.Text.RegularExpressions;

namespace Common.Helpers;

#nullable disable

public class UserAgentParser : ITransientDependency
{
    private readonly HttpClient _httpClient;

    public UserAgentParser(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<string> ParseUserAgentAsync(string userAgent, string ipAddress, string language = "zh-CN")
    {
        if (string.IsNullOrWhiteSpace(userAgent))
        {
            return "Unknown";
        }

        string os = ParseOperatingSystem(userAgent);
        string browser = ParseBrowser(userAgent);
        string location = await GetIpAddressInfoAsync(ipAddress, language);

        return $"{os}-{browser}-{location}";
    }

    private string ParseBrowser(string userAgent)
    {
        if (string.IsNullOrWhiteSpace(userAgent))
        {
            return "Unknown";
        }

        string pattern = @"(MSIE|Edg(?:e)?|Opera|Chrome|Safari|Firefox)(?:/|\s|$)";

        Match match = Regex.Match(userAgent, pattern);
        if (match.Success)
        {
            if (userAgent.Contains("Edg"))
            {
                return "Edge";
            }
            return match.Groups[1].Value;
        }
        return "Unknown";
    }

    private string ParseOperatingSystem(string userAgent)
    {
        if (string.IsNullOrWhiteSpace(userAgent))
        {
            return "Unknown";
        }

        // 操作系统关键词列表
        string[] osKeywords = { "Windows", "Macintosh", "Linux", "Android", "iOS" };

        // 使用正则表达式匹配用户代理字符串中的操作系统关键词
        foreach (string keyword in osKeywords)
        {
            if (userAgent.Contains(keyword))
            {
                return keyword;
            }
        }

        // 如果没有匹配到任何操作系统关键词，则返回 Unknown
        return "Unknown";
    }

    private async Task<string> GetIpAddressInfoAsync(string ipAddress, string language)
    {
        if (ipAddress == "::1" || ipAddress == "127.0.0.1")
        {
            return "本机";
        }

        string apiUrl = $"http://ip-api.com/json/{ipAddress}?lang={language}";
        try
        {
            // 发送 GET 请求并获取响应
            HttpResponseMessage response = await _httpClient.GetAsync(apiUrl);

            // 确保响应成功
            response.EnsureSuccessStatusCode();

            // 读取响应内容并返回
            var responseBody = await response.Content.ReadAsStringAsync();
            dynamic data = JsonConvert.DeserializeObject(responseBody);
            return $"{data.country} {data.regionName} {data.city}";
        }
        catch (HttpRequestException)
        {
            return ipAddress;
        }
    }
}
